<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:background-color="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>聚类算法</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/css/data_plat.css}"/>
    <script type="text/javascript" th:src="@{/js/algo_plat.js}"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
</head>

<style>
    p {
        margin: 0 0 1px;
    }

    table.good{border-collapse:collapse}
    table.good td{border:solid 1px #ccc}
    input.button{border:solid 1px #333;border-radius:50%;padding:0;margin:0;width:auto;font-size:15px;width:20px;height:20px}


</style>
<body>



<div id="form-first">
    <div style="height: 50px;font-size: 30px;text-align: center;font-weight: 600">
        创建KMeans算法模型
    </div>
    <form id="form-algo">
        模型名称：<input id="appName" class="form-control" type="text" th:value="${appName}" name="appName" required placeholder="请输入以'kmeans_'开头的英文名称"><span style="color:red;">*</span><br>
        数据源id:<select id="dataSourceId"  class="form-control"  name="dataSourceId" required onchange="Change_second_selectwords_kmeans();"><span style="color:red;">*</span>
            <option value="0"></option>
            <div th:each="dataBase:${dataBases}">
                <option th:value="${dataBase.id}" th:text="${dataBase.remark}"></option>
            </div>
        </select><br>

        数据表名：
        <select id="tableName" class="form-control"  name="tableName" required onchange="Change_third_selectwords_kmeans();"><span style="color:red;">*</span>
            <!--<div th:each="table:${tableList}">-->
                <!--<option th:value="${table}" th:text="${table}"></option>-->
            <!--</div>-->
        </select><br>

        特征变量的列集合：<span style="color:red;">*</span>
        <!--<div id="trainCols" th:each="metadataColumn:${metadataColumnEntities}">-->
            <!--<input type="checkbox" name="trainCols" th:value="${metadataColumn.columnName}" th:text="${metadataColumn.columnName}"></input>-->
        <!--</div><br>-->
        <div id="featureCols">
        </div><br>

        <div>
            <div>
                <p class="p1">数据预处理策略设置</p>
            </div>
            <div>
                <a onclick="display_pre_process('data_pre_process')">+</a>
            </div>
            <div id="data_pre_process" style="display: none;border: 1px solid #ccc">
                <br>
                <div class="good">
                    <div id="tbEM">
                        <div id="preProcessRow1" class="preProcessRow" style="position:relative;left:5px;bottom: 5px">
                            特征变量：<select id="preProcessFeature" class="form-preprocess-param" name="preProcessMethodList[0].preProcessFeature">
                        </select>
                            预处理策略：<select id="preProcessMethod1" class="form-preprocess-param" name="preProcessMethodList[0].preProcessMethod" onchange="Change_pre_process_method(this);">
                            <option value="deletena">删掉缺失值</option>
                            <option value="fillna">填充缺失值</option>
                            <option value="transType">类型转换</option>
                            <option value="transClassFeature">分类变量转换为数值型变量</option>
                        </select>
                            策略值：<select id="preProcessMethodValue1" class="form-preprocess-param" name="preProcessMethodList[0].preProcessMethodValue">
                        </select>
                            <input type="button" value="+" class="button" onclick="add_pre_process_row()" />
                        </div>
                    </div>
                </div>
            </div>
        </div><br>

        数据无量纲化策略：<select id="standardization" class="form-control" name="standardization">
            <option value=""></option>
            <option value="MinMaxScaler">数据归一化</option>
            <option value="StandardScaler">数据标准化</option>
        </select><br>

        <div>
            <div>
                <p class="p1">模型参数设置</p>
            </div>
            <div>
                <a onclick="display('model_param')">+</a>
            </div>
            <div id="model_param" style="display: none;border: 1px solid #ccc">
                <br>
                <div style="position:relative;left:5px;">
                    聚类个数：<label id="nClustersHyperParame" style="color:#64bd63">获取超参数学习曲线</label>
                    <input class="form-model-param" type="text" name="algoParam.nClusters" placeholder="请输入聚类个数"><br>
                </div>
            </div>
        </div>

        <button type="button" class="btn btn-primary btn-lg btn-block" onclick="pop_up_window()">预览数据</button>
        <button id="createModel" class="btn btn-primary btn-lg btn-block" type="button">创建模型</button>
    </form>

    <!--加载页面-->
    <div id='loader' class="box">
        <img src='/system/img/reload.gif' width='150px' height='150px'>
    </div>

    <!----超参数学习曲线页面-->
    <form id="addparam">
        <p class="addparamp">超参数学习曲线</p>
        <div id="param_values" class="">
            <!--<p>-->
                <!--参数起始值: <input type="text" id="param_start_value" placeholder="请输入起始值" />-->
            <!--</p>-->
            <!--<p>-->
                <!--参数终止值: <input type="text" id="param_end_value" placeholder="请输入终止值" />-->
            <!--</p>-->
            <!--<p>-->
                <!--参数变化间隔: <input type="text" id="param_range_value" placeholder="请输入变化间隔" />-->
            <!--</p>-->
            <!--<br>-->
            <!--<input type="button" value="取消" id="param-train-cancle" /> <input type="button" value="训练" id="param-train" />-->
        </div>
    </form>


</div>


<script>
    var col_list_result = "";
    var index = 2;
</script>
<script>
    $("#createModel").click(function () {
        //判断模型参数不能为空
        var appName = $("#appName").val()
        var tableName = ""
        tableName = $("#tableName option:selected").val()
        var featureCols = ""
        $("input[name='featureCols']").each(
            function(){
                if(this.checked){
                    featureCols = featureCols + $(this).val();
                }
            }
        );

        if (appName.length == 0) {
            alert("模型名称不能为空");
        } else if (tableName == null || tableName == "" || tableName=="undefined") {
            alert("数据表名不能为空");
        } else if (featureCols.length == 0) {
            alert("数据变量的列集合不能为空");
        } else {
            createModel();
        }
    });
    
    function createModel(){
        var strdata = $("#form-algo").serializeObject();

        $.ajax({
            url: "/algo/kmeans/add",
            // data: obj,//传递数据
            async: true,
            type:"post",
            contentType: 'application/json', //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
            dataType: 'json', //表示返回值类型，不必须
            data: JSON.stringify(strdata),//将对象转为json字符串
            success: function (result) {
                if (result["status"] == 0) {
                    model_id = result["modelId"]
                    paramsObj = {modelId: model_id}
                    window.location.href = "/algo/kmeans/result?modelId=" + model_id
//                    axios.get("/algo/kmeans/result", { params: paramsObj })
                } else {
                    //python脚本失败信息
                    $(".addparamp").text("聚类算法聚类失败信息")
                    $("#param_values").empty()
                    var image_html = '<b>'+ result["error"] +'</b>' +
                        '<br><input type="button" value="关闭" id="param-train-cancle" />'
                    $("#param_values").html(image_html)
                    $("#param_values input:first").attr("id", "param-train-cancle")
                    $('#addparam').show();
                    //生成的元素需要重现绑定js函数
                    $("#param_values input:first").click(function () {
                        $('#addparam').hide();
                    })
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown, res) {
                alert(JSON.stringify(res))
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            },
            complete: function(data){   //ajax 完成
                // $("#loading_id").hide();
//                $("div").text(data.responseText);
                $("#loader").hide();
            },
            beforeSend: function(){
                // Show image container
                $("#loader").show();
            },
            catch: function () {
                alert("catch")
            }
        })

    };

    //参数学习页面-训练按钮
    function click_param_train_and_checkparam() {
        //判断模型参数不能为空
        var appName = $("#appName").val()
        var tableName = ""
        tableName = $("#tableName option:selected").val()
        var featureCols = ""
        $("input[name='featureCols']").each(
            function(){
                if(this.checked){
                    featureCols = featureCols + $(this).val();
                }
            }
        );
        if (appName.length == 0) {
            alert("模型名称不能为空");
        } else if (tableName == null || tableName == "" || tableName=="undefined") {
            alert("数据表名不能为空");
        } else if (featureCols.length == 0) {
            alert("数据变量的列集合不能为空");
        } else {
            click_param_train();
        }

    }

    //参数学习页面函数
    function click_param_train() {
        $('#addparam').hide();
        //获取模型参数
        var algo_param = $("#form-algo").serializeObject();
        //获取参数学习参数
        var param_start_value = $("#param_start_value").val()
        var param_end_value = $("#param_end_value").val()
        var param_range_value = $("#param_range_value").val()
        param_train = {}
        param_train["paramName"] = "n_clusters"
        param_train["paramStartValue"] = param_start_value
        param_train["paramEndValue"] = param_end_value
        param_train["paramRangeValue"] = param_range_value
        algo_param["paramTrain"] = param_train

        $.ajax({
            url: "/algo/kmeans/paramtrain",
            // data: obj,//传递数据
            async: true,
            type:"post",
            contentType: 'application/json', //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
            dataType: 'json', //表示返回值类型，不必须
            data: JSON.stringify(algo_param),//将对象转为json字符串
            success: function (result) {
                if (result["status"] == 0) {
                    //python脚本执行成功
                    model_id = result["modelId"]
                    paramsObj = {modelId: model_id}
//                    window.location.href = "/algo/kmeans/paramtrainresult?modelId=" + model_id
//                    axios.get("/algo/kmeans/result", { params: paramsObj })
                    $.get("/algo/kmeans/paramtrainresult?modelId=" + model_id, function (data, status) {
                        var data_json =$.parseJSON(data);
                        if (status == "success") {
                            if (data_json["status"] == "success") {
                                $("#param_values").empty()
                                var image_html = '<img src="/file/'+ data_json["predDisImage"] +'" width="500">' +
                                    '<input type="button" value="关闭" id="param-train-cancle" />'
                                $("#param_values").html(image_html)
                                $("#param_values input:first").attr("id", "param-train-cancle")
                                $('#addparam').show();
                                //生成的元素需要重现绑定js函数
                                $("#param_values input:first").click(function () {
                                    $('#addparam').hide();
                                })
                            } else {
                                $("#param_values").empty()
                                var image_html = '<b>'+ data_json["predDisImage"] +'</b>' +
                                    '<br><input type="button" value="关闭" id="param-train-cancle" />'
                                $("#param_values").html(image_html)
                                $("#param_values input:first").attr("id", "param-train-cancle")
                                $('#addparam').show();
                                //生成的元素需要重现绑定js函数
                                $("#param_values input:first").click(function () {
                                    $('#addparam').hide();
                                })
                            }
                        }
                    })
                } else {
                    //python脚本失败信息
                    $(".addparamp").text("聚类个数--超参数学习曲线失败信息")
                    $("#param_values").empty()
                    var image_html = '<b>'+ result["error"] +'</b>' +
                        '<br><input type="button" value="关闭" id="param-train-cancle" />'
                    $("#param_values").html(image_html)
                    $("#param_values input:first").attr("id", "param-train-cancle")
                    $('#addparam').show();
                    //生成的元素需要重现绑定js函数
                    $("#param_values input:first").click(function () {
                        $('#addparam').hide();
                    })
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown, res) {
                alert(JSON.stringify(res))
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            },
            complete: function(data){   //ajax 完成
                 $("#loader").hide();
//                $("div").text(data.responseText);
            },
            beforeSend: function(){
                // Show image container
                $("#loader").show();
            },
            catch: function () {
                alert("catch")
            }
        })
    }

    //参数学习页面展示
    document.getElementById('nClustersHyperParame').onclick=function(e){
        $('.addparamp').text("聚类个数--超参数学习曲线")
        $('#param_values').empty()
        var param_values_html = '<p>参数起始值: <input type="text" id="param_start_value" placeholder="请输入大于1的整数" /> </p>' +
            '<p>参数终止值: <input type="text" id="param_end_value" placeholder="请输入大于起始值的整数" /> </p>' +
            '<p>参数变化间隔: <input type="text" id="param_range_value" placeholder="请输入整数" /> </p><br>' +
            '<input type="button" value="取消" id="param-train-cancle" /> <input type="button" value="训练" id="param-train" />'
        $('#param_values').html(param_values_html)
        $('#param_values input').eq(0).attr("id", "param_start_value")
        $('#param_values input').eq(1).attr("id", "param_end_value")
        $('#param_values input').eq(2).attr("id", "param_range_value")
        $('#param_values input').eq(3).attr("id", "param-train-cancle")
        $('#param_values input').eq(4).attr("id", "param-train")
        $('#param_values input').eq(3).click(function () {
            $('#addparam').hide();
        })
        $('#param_values input').eq(4).click(function () {
            click_param_train_and_checkparam()
        })
        $('#addparam').show();
    };

    //参数学习页面-取消按钮
    $("#param-train-cancle").click(function() {
        $('#addparam').hide();
    });

</script>
</body>

<script>
    //form表单转json
    $.fn.serializeObject = function () {
        const o = {};
        const a = this.serializeArray();
        $.each(a, function () {
            //增加嵌套属性支持
            const names = this.name.split(".")
            let temp = o;
            // alert("o:" + JSON.stringify(o))
            const end = (names.length - 1);
            //为了支持强制指定单值也可以为json array类型
            const jsonType = $('[name="' + this.name + '"]').data("json-type");
            const jsonArray = jsonType && (jsonType === 'array');
            names.forEach((item, index, array) => {
                // alert("t1:" + item + "," + index+"," + array)
                // alert("t2:" + JSON.stringify(temp))

                item_parent = array[0]
                let isArray = item_parent.endsWith("]")
                // alert("isArray: " + isArray)
                item_index = 0
                if (isArray == true) {
                    if (item.endsWith("]")) {
                        item = item.substring(0,item.lastIndexOf("["))
                    }
                    // alert(item_parent.substring((item_parent.lastIndexOf("[")+1), item_parent.lastIndexOf("]")))
                    item_index = (item_parent.substring((item_parent.lastIndexOf("[")+1), item_parent.lastIndexOf("]")) - 0)
                    // alert("item_index:" + item_index)
                }

                if (temp[item] && isArray==false) {
                    if (index == end) {
                        if (!temp[item].push) {
                            temp[item] = [temp[item]];
                        }
                        temp[item].push(this.value || '');
                    }
                }
                else {
                    if (index == end) {
                        if (isArray) {
                            if (temp[item_index] !== undefined) {
                                temp[item_index][item] = this.value
                            } else {
                                temp[item_index] = {}
                                temp[item_index][item] = this.value
                            }
                        } else {
                            temp[item] = jsonArray ? [this.value || ''] : (this.value || '');
                        }
                        // alert("t3_2:" + JSON.stringify(temp))
                    } else {
                        //新增逻辑
                        if (isArray) {
                            if (!temp[item]) {
                                temp[item] = []
                            }
                        } else {
                            temp[item] = jsonArray ? [] : {};
                        }
                        // alert("t4:" + JSON.stringify(temp))
                    }
                }
                temp = temp[item];
            })
        });
        return o;
    };
</script>

</html>
